var addrbill = require('../../../sys/sys_addr.js')
var locationclient = require('../../../sys/locationclient.js')
var behaviorsbasicform = require('../../behavior/basicform')

var acttoolxv2 = require('../../../sys/toolv2');
var userlocationv2 = require('../../../../xc/sys/location/userlocationv2')

Component({
  behaviors: [behaviorsbasicform],
  options: {
    addGlobalClass: true,
    multipleSlots: true
  },
  /**
   * 组件的属性列表
   */
  properties: {
    delivery_config:{
      type:Object,
      value:null
    },
    optype: {
      type: String,
      value: "full"       //nohead //full
    },
    show:{
      type: Boolean,
      value: true
    },
    // optype: {
    //   type: Object,
    //   value:{ openloacion: -1 }      //nohead //full
    // },  
    navCur: {
      type: String,
      value: "0",
      observer: function(newVal, oldVal){
        if(newVal==3&&newVal!==oldVal){

          this.calcdistance();

        }         

      }
    },
    themcolor: {
      type: Object,
      default: {}
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    op: "",

    issubmited: false,
    model: {},
    phoneallow:-1,
  },
  ready() {
    var app = getApp();
    
    if(app.globalData.configdata && app.globalData.configdata.order && app.globalData.configdata.order.phone){
       this.setData({
        phoneallow:app.globalData.configdata.order.phone
       })
    }



  },

  /**
   * 组件的方法列表
   */
  methods: {

    
    loadaddr() {
      
      var that = this;
      
      var model = that.data.model
      var app = getApp();
      if (app.globalData.member.memberinfo) {
        model["name"] = app.globalData.member.memberinfo.name
        model["phone"] = app.globalData.member.memberinfo.phone
      }
     
      var that =this;
      userlocationv2.lastaddr().then(function(resut){  
        if(resut["status"]==1){
          that.transformlocationaddr(model,resut.obj)
        }else{
          that.setData({ model })
          if(that.data.optype=="nohead"){
            that.triggerEvent("noheadchange",model)
          }
        }
       })
 


     
    },
    transformlocationaddr(model,addinfo){
   
      var that=this;
      
      var that =this;
      model["city"] = addinfo["city"]
      model["county"] = addinfo["district"]
      model["countycode"] = addinfo["adcode"]
      model["province"] = addinfo["province"]
      model["lat"] = addinfo["lat"]
      model["lng"] = addinfo["lng"]
      model["addrinfo"] = addinfo["addrinfo"]
      model["addrname"] = addinfo["addrname"]
      
      if( addinfo["lat"] && this.data.navCur ==3){
        var  intracity =this.data.delivery_config.intracity
        var app =getApp()
        var distance =app.toolv2.distanceByLnglat(model.lng,model.lat,intracity.lng,intracity.lat)
        model["distance"] =distance
      
      } 
      that.setData({ model })
      if(that.data.optype=="nohead"){
        that.triggerEvent("noheadchange",model)
      }
     
    },
    calcdistance(){

      var model = this.data.model;
      var updatemodel={};      
      if( this.data.navCur==3 && model.lat>0)
      {
        var  delivery_config = this.data.delivery_config
        var  intracity =delivery_config.intracity
        var app = getApp();
        var distance =app.toolv2.distanceByLnglat(model.lng,model.lat,intracity.lng,intracity.lat)
      
        updatemodel['model.distance']=distance
       
      }
      else
      {
        updatemodel['model.distance'] =null;
      } 
      this.setData(updatemodel)          
    },


    showop(op, model, waddr) {
      var that=this;
      console.log(" showop(op, model, waddr)")

      // if(wx.onNeedPrivacyAuthorization){
      //   wx.onNeedPrivacyAuthorization((resolve, eventInfo) => {
      //     console.log('触发本次事件的接口是：' + eventInfo.referrer)
      //     // 需要用户同意隐私授权时
      //     // 弹出开发者自定义的隐私授权弹窗
      //     that.selectComponent("#privacypopup").show()
      //     // this.setData({
      //     //   showPrivacy: true
      //     // })
      //     this.resolvePrivacyAuthorization = resolve
      //   })
      // }
      this.loadaddr();

      var updatemodel = {}
      updatemodel["op"] = op;
      if (!model) {
        model = this.clearmodel(true)
      }
      if (waddr) {
        model = this.transformwaddr(model, waddr)
      }
      updatemodel["model"] = model
      updatemodel["issubmited"] = false
      this.setData(updatemodel)
    },
    // handleAgreePrivacyAuthorization() {
    //   console.log("ssssssssssssssss")
    //   var that=this;
    //   if(wx.onNeedPrivacyAuthorization){
    //     console.log("ssssssssssssssssssssss")
    //     that.selectComponent("#privacypopup").show()
        
    //     wx.onNeedPrivacyAuthorization(
    //       (resolve, eventInfo) => {
    //       console.log("ssssssssssssssssssssss")
    //       console.log(resolve)
    //       console.log(eventInfo)
         
    //       console.log('触发本次事件的接口是：' + eventInfo.referrer)
    //       // 需要用户同意隐私授权时
    //       // 弹出开发者自定义的隐私授权弹窗
    //       that.selectComponent("#privacypopup").show()
    //       // this.setData({
    //       //   showPrivacy: true
    //       // })
    //       this.resolvePrivacyAuthorization = resolve
    //     })
    //   }
    // },
    // agree() {
    //   // 用户点击同意按钮后
    //   this.resolvePrivacyAuthorization({ buttonId: 'agree-btn', event: 'agree' })
    //   // 用户点击同意后，开发者调用 resolve({ buttonId: 'agree-btn', event: 'agree' })  告知平台用户已经同意，参数传同意按钮的id
    //   // 用户点击拒绝后，开发者调用 resolve({ event:'disagree' }) 告知平台用户已经拒绝
    // },
    // disagree(){
    
    //   this.resolvePrivacyAuthorization({event:'disagree' })

    //    wx.showToast({
    //      type:"error",
    //      title: '已拒绝',
    //    })
    // },
    transformwaddr(model, waddr) {
     

      model["province"] = waddr["provinceName"]
      model["city"] = waddr["cityName"]
      model["county"] = waddr["countyName"]
      model["addrinfo"] = waddr["detailInfo"]
      model["name"] = waddr["userName"]
      model["phone"] = waddr["telNumber"]
      model["countycode"] = waddr["nationalCode"]

      return model;
    },

    hideform() {
      this.setData({ op: '' })

    },

    chooseLocation(ev) {
    console.log("chooseLocation")
    console.log(ev)
  
      var mydata = ev;
      var that = this;

      

      var model = that.data.model
      model["province"] = ev.province;
      model["city"] = ev.city;
      if(ev.district){
        model["county"] = ev.district;
      }else{
        model["county"] = ev.city;
      }
      model.addrname = mydata["name"];
      model.addrinfo = mydata["address"];
      model.lat = mydata["latitude"];
      model.lng = mydata["longitude"];
      that.setData({ model })
      this.calcdistance();

      if(that.data.optype=="nohead"){
        that.triggerEvent("noheadchange",model)
      }

    },
    chosepostion: function (e) {
      var delivery_config = this.data.delivery_config
      var model = this.data.model
      if (delivery_config.loaciontype == 1) {
        var qqstylemap = this.selectComponent("#qqstylemap")
        var mode = 1;
        if (this.data.navCur == 3) {
          //域名限制
          mode = 2
        }

        
        qqstylemap.showmap(mode, model, delivery_config.intracity)
        return;
      } else if (delivery_config.loaciontype == 2) {
        var app = getApp();
        try {
          var mapqq = app.globalData.configdata.map.qq
          var url = 'plugin://chooseLocation/index?key=' + mapqq.key + '&referer=' + mapqq.keyname
          if (model.lat && model.lat != 0) {
            const location = JSON.stringify({
              latitude: model.lat,
              longitude: model.lng
            });
            url += '&location=' + location
          }
       
          wx.navigateTo({
            url
          });


        }
        catch (ex) {

       

          wx.showToast({
            title: '请检测腾讯地图配制是否正确',
          })
        }
      }
      return
    },
    chooseaddress: function (e) {
  

      var that=this;
      var data = e.detail;
      var model = this.data.model;
      model.province = data[0].name;
      model.city = data[1].name;
      model.county = data[2].name;
      model.countycode = data[2].id;
      this.setData({ model })

      if(that.data.optype=="nohead"){     
        that.triggerEvent("noheadchange",model)
      }
    },
    //选择地区
    pickerblock: function () {
      var model = this.data.model
      this.selectComponent("#picker").setinitdata(model.province, model.city, model.county);
    },
    //地址提交
    addrfromsubit(e,resolve) {
      var model = this.data.model;
      var that = this;
      if(!resolve)
      {
        resolve=function(nreslt){
      
        }
      }
      


        if (that.data.navCur == 3) {

          if (model.lat == 0 || !model.lat) {
            wx.showToast({
              title: '请选择地址',
            })

            resolve({status:-1})
  
            return
          }
        }
  
       
        var vdata = {
          "name": ["", "收货人姓名不能为空"],
          "phone": ["", "手机不能为空"],
          "addrinfo": ["", "详细地址不能为空"]
        }
        var errors = [];
        for (var a in vdata) {
          if (!model[a] || model[a] == vdata[a][0]) {
            errors.push(vdata[a][1])
          }
        }
  
        if (errors.length > 0) {
          wx.showModal({
            title: '错误',
            content: errors.join("\r\n"),
          })
          that.setData({ issubmited: true })
          resolve({status:-1})
        }
        else {
          if ((!model.county) || (!model.province) || (!model.city)) {
            wx.showModal({
              title: '错误',
              content: "请选择地区",
            })
            this.setData({ issubmited: true })
            resolve({status:-1})
            return false;
          }
          addrbill.addormodify(model).then(function (ret) {
            console.log("addormodifydddddddddd")
            console.log(ret)
            if (ret["code"] == "success" && ret["status"]==1) {
              if (model.id == 0 || !model.id) {
                model.id = ret["id"]
              }
              that.triggerEvent("addfun", model)

             

             if(that.data.optype!='nohead')  
             {
              wx.showToast({
                title: '操作成功',
              })
             }         
              that.setData({ op: "" })
              resolve({status:1,obj:model})
            }
            else
            {
              resolve({status:-1})
              wx.showToast({
                title: '操作失败',
              })
            }
         
          }
          )
        }
       

    },

    selectedaddr(ev) {
     
      var that = this;
      var detail = ev.detail
      var model = that.data.model
      for (var a in detail) {
        model[a] = detail[a];
      }
      that.setData({ model })
      this.calcdistance();


      if(that.data.optype=="nohead"){that.triggerEvent("noheadchange",model)}

    },
    //清空数据
    clearmodel(black) {
      var clearupdate = {
        addrmodel: {
          isdefault: "-1",
          addrinfo: "",
          lat: 0,
          lng: 0,
          region: [],
          phone: "",
          name: ""
        }
      }
      if (black) {
        return clearupdate.addrmodel
      }
      else {
        this.setData(clearupdate)
      }
    }
  }
})
